//
//  HJCOAuthViewController.swift
//  新浪微博Swift
//
//  Created by 郝俊聪 on 15/5/12.
//  Copyright (c) 2015年 heima. All rights reserved.
//

/*
App Key:2276300886
App Secret : b38c7bf588b06646b1b7907437999e6c
URL : https://api.weibo.com/oauth2/authorize
回调地址：http://www.itcast.com
*/

import UIKit
import SVProgressHUD

class HJCOAuthViewController: UIViewController ,UIWebViewDelegate{
    
    @IBAction func closeOAuthView()
    {
        dismissViewControllerAnimated(true, completion: { () -> Void in
            
        SVProgressHUD.dismiss()
            
        })
    }
    
    var webView : UIWebView
    {
        return view as! UIWebView
    }
    

    let client_id : String = "2276300886"
    let redirect_uri : String = "http://www.itcast.com"
    let client_secret : String =  "b38c7bf588b06646b1b7907437999e6c"
//    let client_id : String = "432361796"
//    let redirect_uri : String = "http://ubox.cn"
//    let client_secret : String =  "b85d5894b4de5aef220d074ea4993322"
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        webView.delegate = self

    
    }


    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        
        let request = NSURLRequest(URL: NSURL(string: urlStr)!)
        
        webView.loadRequest(request)
        
    }
    /*
    加载登录页面：https://api.weibo.com/oauth2/authorize?client_id=2276300886&redirect_uri=http://www.itcast.com
    注册：http://weibo.cn/dpool/ttt/h5/reg.php?wm=4406&app
    登录：https://api.weibo.com/oauth2/authorize
    取消：http://itheima.com/?error_uri=%
    授权：http://www.itcast.com/?code=78a68033223c738a9c60be85dd381831
    切换账号：http://login.sina.com.cn/sso/logout.php?
    
    
    */
    
    //MARK: - UIWebViewDelegate
    //拦截request请求
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
//        println(request.URL)
        //取得URL的完整字符串
        let urlStr = request.URL!.absoluteString!
        
        //是官方页面，继续加载
        if urlStr.hasPrefix("https://api.weibo.com/")
        {
            return true
        }
        
        //不是回调页面，直接返回，不加载
        if !urlStr.hasPrefix(redirect_uri)
        {
            return false
        }
        
        //执行到这里，一定是回调请求啦
//        println("-->"+request.URL!.query!)
        
        //取得url中得参数
        let query = request.URL!.query!
        
        //如果是取消，则关闭页面
        if  query.hasPrefix("error_uri")
        {
            closeOAuthView()
            SVProgressHUD.dismiss()
        }
        
        
        let codeStr = "code="
        
        //如果点了授权按钮，获取许可
        if query.hasPrefix(codeStr)
        {
            let code = (query as NSString).substringFromIndex(codeStr.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
            
            //获得AccessToken
            let para = ["client_id":client_id,
                "client_secret":client_secret,
                "grant_type":"authorization_code",
                "code":code,
                "redirect_uri":redirect_uri,
            ]
            
            UserAccount.loadAccountToken(para, finished: { (account) -> () in
                
                if account == nil
                {
                    SVProgressHUD.showErrorWithStatus("你的网速不给力哦")
                }else
                {
                    //登入,给全局账户名赋值
                
                    sharedaccount = account
                    
                    //发送通知，切换界面
                    NSNotificationCenter.defaultCenter().postNotificationName(NSSWICTHCONTRONLLERNOTIFICATION, object: "Welcome")
                    
                    
                    //关闭webviewC
                    self.closeOAuthView()
                }
       
            })
            
        }
        
        
        return false
    }
    
    

    
    
    
    //加载网页时
    func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD.show()
    }
    
    //加载结束
    func webViewDidFinishLoad(webView: UIWebView) {
        
        SVProgressHUD.dismiss()
    }
    

}
